package com.example.portablefortheelderlybackground.sevice.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.portablefortheelderlybackground.common.User.loadUserDetails;
import com.example.portablefortheelderlybackground.pojo.user;
import com.example.portablefortheelderlybackground.sevice.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;


@Service
@Slf4j
public class userDetailServiceImpl implements UserDetailsService {
    private final userService userService;

    private final menuService menuService;

    private final userRoleService userRoleService;

    private final roleMenuService roleMenuService;

    @Autowired
    public userDetailServiceImpl(userService userService, menuService menuService, userRoleService userRoleService, roleMenuService roleMenuService) {
        this.userService = userService;
        this.menuService = menuService;
        this.userRoleService = userRoleService;
        this.roleMenuService = roleMenuService;
    }

    /**
     * @param username 用户名
     * @return org.springframework.security.core.userdetails.UserDetails
     * @description: 查询用户, 进行权限的查询, 封装
     * @author 86187
     * @date: 2023/5/19 17:09
     */

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<user> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasText(username), user::getName, username);
        user user = userService.getOne(queryWrapper);
        System.out.println("user--->" + user.toString());
        //对用户进行判断
        if (ObjectUtils.isEmpty(user)) {
            log.info("用户名不存在");
            return null;
        }
        //将user注入到userDetailImpl中
        //进行权限的封装--查询数据库
        //根据用户名查询roleId
        return loadUserDetails.getUserDetails(userRoleService, roleMenuService, menuService, user);
    }
}
